<template>
  <view class="page index-page rec-bag-pop-page">
    <uni-navbar
      title="福利中心"
      :border="false"
      :fixed="true"
      :height="barHeight"
      :rightWidth="60"
      :leftWidth="60"
      :leftIcon="!isMpWeixinH5"
      titleStyle="color:#fff;fontSize:18px;"
      :bgColor="isWhiteAppBar ? '#FF5500' : 'transparent'"
      :placeholder="false"
      :autoBack="false"
      :backNative="true"
    >
      <template #left>
        <image v-if="isH5 && !isMpWeixinH5" src="../../static/images/back_white2.png" class="back-icon" style="margin-left: -10rpx;"></image>
        <span v-else></span>
      </template>
    </uni-navbar>

    <scroll-view
      class="box-1"
      :scroll-y="true"
      :refresher-enabled="false"
      :style="{paddingTop: headHt}"
      refresher-background="#ffffff"
      @scroll="scrollEv"
    >
      <view v-if="!isLogin" 
        style="text-align: center;margin-top: 60rpx;color: #fff;font-size: 36rpx;" 
        @tap="toLogin"
      >
        您尚未登录，前往登录>>
      </view>
      <view v-if="isLogin" style="position:relative;">
        <view style="padding-left:48rpx;color:#fff;text-align:left;align-items: flex-end;" class="flex" @tap="toCoinDetails">
          <text style="font-size: 80rpx;height:80rpx; line-height: 80rpx;margin-right:16rpx;" @click="toMyCoin">{{golds}}</text>
          <text>金币</text>

          <view class="real-money"> 
            <text class="text-3">{{moneyNum}}</text>
            <text class="text-4">元</text>
          </view>
        </view>

        <!-- <view style="padding-left:48rpx;color:#fff;text-align:left;font-size:24rpx;margin: 12rpx 0 16rpx;">
          每日最少可提现0.3元
        </view> -->

        <view class="withdraw-btn">
          <text @click="toWithDraw">提现</text>
        </view>

        <view style="min-height:56rpx;"> 
          <u-notice-bar 
            mode="vertical" 
            duration="2500" 
            :list="msgList"
            color="#fff" bg-color	="#00000000" 
            font-size="24" 
            :volume-icon="false" 
            padding="32rpx 0rpx 0rpx 48rpx"
          ></u-notice-bar>
        </view>
        <image class="ic-box-money" :src="staticHost+'/money-box.png'" mode="widthFix"></image>

        <view class="sign-center">
          <view class="h2-t">连续签到7天参与抽取88元现金红包</view>
          <view class="remark">每日签到领取红包，福利领不完</view>
          <view class="sign-days">
            <view v-for="(obj, index) in coinList" :key="index" :class="['day-item',index == coinList.length-1 ? 'last-box':'']">
              <view v-if="index == coinList.length-1" :class="['day-box', obj.finished ? 'finished':'', index+1 == obj.current ? 'curr':'']" >
                <image class="redbag" :src="staticHost + '/redenvelope.png'" mode="widthFix"></image>
                <image class="done" v-if="obj.finished" :src="staticHost + '/done_check.png'" mode="widthFix"></image>
                <view class="redbag-amount">最高88元现金红包</view>
              </view>
              <view v-else :class="['day-box', obj.finished ? 'finished':'',index+1 == obj.current ? 'curr':'']" >
                <image class="coin" :src="staticHost + '/coin.png'" mode="widthFix"></image>
                <image class="done" v-if="obj.finished" :src="staticHost + '/done_check.png'" mode="widthFix"></image>
                <view class="coin-num">
                  {{ obj.coinNum }}
                </view>
              </view>
              <view class="day-txt">{{('第'+(index+1)) }}天</view>
            </view>
          </view>
          <view style="text-align:center;">
            <view :class="['sign-btn', (coinInfo.cmped && cg) ? 'disable': '']"
              @click="toCheckIn">{{ coinInfo.cmped ? cg ? '已签到' : '继续赚取百元金币' : '签到' }}
            </view>
          </view>
        </view>

        <view class="rules">
          <view class="font16 font-b" style="margin-bottom:10rpx;">签到规则</view>
          <view class="font12 cor-grey" v-for="(ruleStr ,index) in signRuleList " :key="index">
            {{ruleStr}}
          </view>
        </view>
      </view>
      <view style="width:100%;height:20rpx"></view>
    </scroll-view>
    <SignRedbag :eventName="eventName" @receiveSuccess="getSignCenterData"></SignRedbag>
  </view>
</template>

<script>
import { isMpWeixin, isMpAlipay, isMpBaidu, isMpToutiao, isMpKuaishou, isH5 } from '@/utils/platform';
import statusBarInfo from '@/pages/welfare/mixins/statusBarInfo'
import SignRedbag from './components/SignRedbag';

const app = getApp();
// import { encryptFn } from '@/utils/index'
// import { getRandomInt } from '@/utils/util'
import { SignNew, SignCenterData } from '@/pages/welfare/api/index';
import { serviceMobile, staticHost } from '@/setting';

export default {
  mixins: [ statusBarInfo ],
  components: {
    SignRedbag
  },
  computed: {
    moneyNum() {
      if (this.golds) {
        return this.golds / 1000;
      }
      return 0;
    }
  },
  data() {
    return {
      isMpWeixin,
      isMpAlipay,
      isH5,
      contactsMobile: serviceMobile,
      isWhiteAppBar: false,
      staticHost,
      isLogin: true,
      isMpWeixinH5: false,
      eventName: 'Welfare',
      coinList: [
        { id: 1, coinNum: "1000+", current: 0, finished:0 },
        { id: 2, coinNum: "？",current: 0, finished:0},
        { id: 3, coinNum: "？" ,current: 0, finished:0},
        { id: 4, coinNum: "？" ,current: 0, finished:0},
        { id: 5, coinNum: "？" ,current: 0, finished:0},
        { id: 6, coinNum: "？" ,current: 0, finished:0},
        { id: 7, coinNum: "？",current: 0, finished:0},
      ],
      coinInfo: { },
      cg: 0,
      golds:0,
      signRuleList:[],
      menuBottom: isMpAlipay ? 16: 0,
      msgList:[]
    };
  },
  onLoad() {
    uni.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    let _self = this;
    if (isMpWeixin || isMpBaidu || isMpAlipay || isMpToutiao || isMpKuaishou) {
      let userInfo = app.globalData.userInfo;

      if (userInfo && userInfo.userId) {
        if (this.$uma && this.$uma.trackEvent) {
          this.$uma.trackEvent('enter_sign', userInfo);
        }
      }
      
      if (!userInfo || !userInfo.userId) {
        setTimeout(() => {
          // 跳转登录
          this.$navigateTo('/pages/login/phone')
        }, 1000)
      }
    }
    
    function ready() {
      console.log('ready 是否是小程序::', window.__wxjs_environment === 'miniprogram');
      if (window.__wxjs_environment === 'miniprogram') {
        // 是小程序环境
        _self.isMpWeixinH5 = true;
      }
    }
    if (isH5) {
      setTimeout(() => {
        if (!window.WeixinJSBridge || !window.WeixinJSBridge.invoke) {
          console.log('开始监听window.ev.WeixinJSBridgeReady');
          document.addEventListener('WeixinJSBridgeReady', ready, false)
        } else {
          ready()
        }
      }, 500)
    }
  },
  onShow() {
    if (isMpWeixin || isMpAlipay || isMpBaidu || isMpToutiao || isMpKuaishou) {
      let userInfo = app.globalData.userInfo;
      if (userInfo && userInfo.userId) {
        this.isLogin = true;
      } else {
        this.isLogin = false;
      }
    }
    
    this.getSignCenterData()
    uni.$emit(`onShow${this.eventName}`, '福利中心');
    setTimeout(() => {
      uni.$emit(`onShow${this.eventName}`, '福利中心');
    }, 800)
  },
  options: { styleIsolation: 'shared' },
  methods: {
    toLogin() {
      this.$navigateTo('/pages/login/phone')
    },
    toCoinDetails() {
      this.$navigateTo('/pages/welfare/coinDetails')
    },
    getSignCenterData() {
      SignCenterData().then(res => {
        this.cg = res.cg;
        if (res.code == 200 && res.data) {
          let { golds, msgList, items = [], curItem, signRule } = res.data
          
          let len = items.length;
          if (curItem) {
            let obj = this.coinList[curItem.signIndex-1]  
            obj.current = curItem.signIndex;
            if (curItem.golds) {
              obj.finished = curItem.cmped;
              obj.coinNum = curItem.golds;
            }
            console.log('obj.finished > ',obj.finished);
          } else if (len){
            this.coinList[len].current = len+1;
          } else {
            this.coinList[0].current = 1;
          }
          
          for(let i = 0; i < this.coinList.length; i++) {
            let el = this.coinList[i]
            let result = items[i];
            if (result && result.golds) {
              el.finished = result.cmped
              if (result.cmped) {
                el.coinNum = result.golds;
              }
            }
          }

          this.setData({
            coinInfo: curItem || {},
            golds,
            msgList,
            coinList: this.coinList
          })
          
          if(signRule){
            let rows = [];
            if(signRule.indexOf("\n")!=-1){
              let tipList = signRule.split("\n")
              rows.push(...tipList)
            }else{
              rows.push(signRule)
            }
            this.signRuleList = rows; 
          }
          console.log("coinList==="+JSON.stringify(this.coinList))
        }
      })
    },
    toMyCoin() {
      // this.common.routerPush('/myCoin')
    },
    toWithDraw() {
      this.$navigateTo('/pages/welfare/withdrawal');
    },
    toCheckIn() {
      let items = this.coinList.filter(item => item.current > 0)
      // 是否第一天
      let firstDay = true;
      if (items.length && items[items.length-1].current > 1) {
        firstDay = false;
      }
      
      if (this.cg) {
        if (this.coinInfo.cmped && firstDay) {
          this.$showToast('今日已完成签到')
          return;
        }
      }
      
      SignNew({}).then(res => {
        if (res.code == 200) {
          if (res.data.id) {
            this.$navigateTo('/pages/welfare/signCenter?signId=' + res.data.id);
          }
        }
      })
    },
    scrollEv(e) {
      // console.log('scrollEv', e);
      let scrollTop =  e.target.scrollTop
      if (typeof scrollTop === 'number') {
        if (scrollTop > 50) {
          // tabbar背景切换
          this.isWhiteAppBar = true;
        } else {
          this.isWhiteAppBar = false;
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
  .index-page {
    width: 100%;
    background-color: #fff;
    overflow: hidden;
    height: 100%;

    v-deep .u-swiper {
      margin-left: 0;
    }

    .box-1 {
      position: relative;
      margin-bottom: 16rpx;
      background: linear-gradient(180deg,#f50,#F9EEE7);
      height: 100%;

      .real-money {
        padding: 8rpx 12rpx;
        margin-left: 10px;
        background: #F8EDED;
        color: #f50;
        border-radius: 28rpx 28rpx 28rpx 4rpx;
        font-size: 12px;
        font-weight: 700;
      }

      .withdraw-btn {
        margin-left:48rpx;
        margin-top: 32rpx;
        width:126rpx;
        height:48rpx;
        line-height:48rpx;
        border: 1px solid #fff;
        border-radius: 24rpx;
        text-align: center;
        color:#fff;
      }
      .ic-box-money {
        position: absolute!important;
        top: 0rpx;
        right: 0;
        width: 332rpx;
      }

      .sign-center {
        background: #fff;
        margin: 0 32rpx;
        padding: 32rpx 0 32rpx 32rpx;
        border-radius: 32rpx;
        text-align: left;
        margin-top: 40rpx;

        .h2-t {
          font-size: 32rpx;
          font-weight: bold;
          margin-bottom: 8rpx;
        }
        .remark {
          font-size: 24rpx;
          color: $grey_color;
          margin-bottom: 30rpx;
        }
        .sign-days {
          display: flex;
          flex-wrap: wrap;

          .day-item {
            width: calc((100% - 128rpx) / 4);
            margin-right: 32rpx;

            &.last-box {
              width: calc((100% - 64rpx) / 2);
            }



            .day-box {
              position: relative;
              width: 100%;
              height: calc((100vw - 128rpx - 128rpx) / 4);
              background: #F8EDED;
              border-radius: 24rpx;
              text-align: center;

              .done {
                position: absolute;
                z-index: 2;
                width: 36rpx;
                left: 0;
                right: 0;
                margin: 30rpx auto 0;
              }

              &.finished {
                background: #FF7733;
                color: #fff;
              }
              &.curr{
                border: 2rpx solid #FF7733;;
              }

              .coin {
                width: 48rpx;
                height: 48rpx;
                margin-top: 24rpx;
              }
              .coin-num {
                font-size: 24rpx;
                line-height: 24rpx;
              }
              .redbag {
                width: 44rpx;
                margin-top: 20rpx;
              }
              .redbag-amount {
                font-weight: bold;
                font-size: 24rpx;
                line-height: 24rpx;
              }
            }
            .day-txt {
              text-align: center;
              color: $grey_color;
              width: 100%;
              margin-top: 16rpx;
              margin-bottom: 24rpx;
            }
          }
        }
        .sign-btn {
          display: inline-block;
          min-width: 240rpx;
          padding: 0 72rpx;
          height: 64rpx;
          line-height: 64rpx;
          border-radius: 40rpx;
          margin-top: 24rpx;
          background: #F65352;
          font-weight: 500;
          color: #fff;
          // margin: 0 auto;
          text-align: center;

          &.disable {
            background: #CCCCCC;
            color: #fff;
          }
        }
      }

      .rules {
        background: #FFFFFF;
        box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(77,14,0,0.2);
        border-radius: 32rpx;
        margin: 32rpx 32rpx 48rpx;
        padding: 32rpx 32rpx 48rpx;
      }
    }
  }
</style>
